<?php
namespace app\lib\exception;

use think\Exception;
use think\exception\Handle;
use think\Log;
use think\Request;

class ExceptionHandler extends Handle {
    private $code;
    private $msg;
    private $errorCode;

    //需要返回客户端当前请求的URL路由地址
    //自定义错误重写
    public function render(\Exception $e){
        //        object instanceof class 某对象属于某类
        if($e instanceof baseException){
            //如果是自定的异常，向客户端返回信息
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{

            if(config('app_debug')){
                return parent::render($e);
            }

            $this->code = 500;
            $this->msg = '服务器内部错误，不想告诉你';
            $this->errorCode = 9999;
            $this->recordErrorLog($e);//只有在服务器内部报错的时候才使用日志记录错误
        }
        $request = Request::instance();
        $result = array(
            'msg'=>$this->msg,
            'error_code'=>$this->errorCode,
            'request_url'=>$request->url(),
        );
        return json($result,$this->code);
    }


    private function recordErrorLog(\Exception $e){
        Log::init(array('type'  => 'File',
            'path'  => LOG_PATH,
            'level' => ['error'],));
        Log::record($e->getMessage(),'error');//tp5获取日志的方法
    }



}



